//
//  SVWebViewController.m
//
//  Created by Sam Vermette on 08.11.10.
//  Copyright 2010 Sam Vermette. All rights reserved.
//
//  https://github.com/samvermette/SVWebViewController

#import "SVWebViewController.h"
#import "Reachability.h"
#import "Config.h"
@interface SVWebViewController () <UIWebViewDelegate, UIActionSheetDelegate, MFMailComposeViewControllerDelegate>

@property (nonatomic, strong, readonly) UIBarButtonItem *backBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *forwardBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *refreshBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *stopBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *homeBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *actionBarButtonItem;
@property (nonatomic, strong, readonly) UIActionSheet *pageActionSheet;
@property (nonatomic, strong) NSHTTPCookieStorage *cook;
@property (nonatomic, strong) UIWebView *mainWebView;
@property (nonatomic, strong) NSURL *URL;

- (id)initWithAddress:(NSString*)urlString;
- (id)initWithURL:(NSURL*)URL;

- (void)updateToolbarItems;

- (void)goBackClicked:(UIBarButtonItem *)sender;
- (void)goForwardClicked:(UIBarButtonItem *)sender;
- (void)reloadClicked:(UIBarButtonItem *)sender;
- (void)stopClicked:(UIBarButtonItem *)sender;
- (void)actionButtonClicked:(UIBarButtonItem *)sender;

@end


@implementation SVWebViewController
@synthesize _progressView;
@synthesize _progressProxy;

@synthesize availableActions;

@synthesize URL, mainWebView;
@synthesize backBarButtonItem, forwardBarButtonItem, refreshBarButtonItem, stopBarButtonItem,homeBarButtonItem, actionBarButtonItem, pageActionSheet;

#pragma mark - setters and getters

- (NSHTTPCookieStorage *)cook {
    if (!_cook) {
        _cook = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    }
    return _cook;
}
- (UIBarButtonItem *)backBarButtonItem {
    
    if (!backBarButtonItem) {
        UIButton *back = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [back setImage:[UIImage imageNamed:@"back_02"] forState:UIControlStateNormal];
        [back addTarget:self action:@selector(goBackClicked:) forControlEvents:UIControlEventTouchUpInside];
        backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
        
    }
    return backBarButtonItem;
}

- (UIBarButtonItem *)forwardBarButtonItem {
    
    if (!forwardBarButtonItem) {
        UIButton *forward = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [forward setImage:[UIImage imageNamed:@"go_02"] forState:UIControlStateNormal];
        [forward addTarget:self action:@selector(goForwardClicked:) forControlEvents:UIControlEventTouchUpInside];
        forwardBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:forward];
    }
    return forwardBarButtonItem;
}

- (UIBarButtonItem *)refreshBarButtonItem {
    
    if (!refreshBarButtonItem) {
        UIButton *refresh = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [refresh setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
        [refresh addTarget:self action:@selector(reloadClicked:) forControlEvents:UIControlEventTouchUpInside];
        refreshBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:refresh];
    }
    
    return refreshBarButtonItem;
}


- (UIBarButtonItem *)homeBarButtonItem {
    if (!homeBarButtonItem) {
        UIButton *home = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [home setImage:[UIImage imageNamed:@"home-1"] forState:UIControlStateNormal];
        [home addTarget:self action:@selector(homeClicked:) forControlEvents:UIControlEventTouchUpInside];
        homeBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:home];
    }
    return homeBarButtonItem;
}


- (UIBarButtonItem *)actionBarButtonItem {
    
    if (!actionBarButtonItem) {
        UIButton *action = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [action setImage:[UIImage imageNamed:@"logout"] forState:UIControlStateNormal];
        [action addTarget:self action:@selector(actionButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        actionBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:action];
    }
    return actionBarButtonItem;
}


#pragma mark - Initialization

- (id)initWithAddress:(NSString *)urlString {
    return [self initWithURL:[NSURL URLWithString:urlString]];
}

- (id)initWithURL:(NSURL*)pageURL {
    
    if(self = [super init]) {
        self.URL = pageURL;
        self.availableActions = SVWebViewControllerAvailableActionsOpenInSafari | SVWebViewControllerAvailableActionsMailLink;
    }
    
    return self;
}

#pragma mark - Memory management

- (void)dealloc {
    mainWebView.delegate = nil;
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

#pragma mark - View lifecycle

- (void)loadWebView {
    mainWebView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    mainWebView.delegate = _progressProxy;
    mainWebView.scalesPageToFit = YES;
    mainWebView.scrollView.bounces = NO;
    NSLog(@"%@",self.URL);
     [self.cook setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.autoyou.com.cn/home"]];
    [request setValue:self.token forHTTPHeaderField:@"X-CSRF-TOKEN"];
    [mainWebView loadRequest:request];
    self.view = mainWebView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar addSubview:_progressView];
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    CGFloat progressBarHeight = 2.f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    

    self.title = @"悠享车生活";
    self.navigationController.hidesBarsOnSwipe = YES;

    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        self.edgesForExtendedLayout = UIRectEdgeBottom;//枚举可视情况更换top all none bottom
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    mainWebView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        mainWebView.delegate = _progressProxy;
    mainWebView.scalesPageToFit = YES;
    mainWebView.scrollView.bounces = NO;
    NSLog(@"%@",self.URL);
    [self.cook setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.autoyou.com.cn/home"]];
    [request setValue:self.token forHTTPHeaderField:@"X-CSRF-TOKEN"];
    [mainWebView loadRequest:request];
    [self.view addSubview:mainWebView];
    Reachability *r= [Reachability reachabilityForInternetConnection];
    if ([r currentReachabilityStatus] == NotReachable) {
        [Config showMessage:@"您当前网络不给力,请稍后再试!"];
    }

    [self updateToolbarItems];
}

- (void)viewDidUnload {
    
    [super viewDidUnload];
    mainWebView = nil;
    backBarButtonItem = nil;
    forwardBarButtonItem = nil;
    refreshBarButtonItem = nil;
    stopBarButtonItem = nil;
    actionBarButtonItem = nil;
    pageActionSheet = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    NSAssert(self.navigationController, @"SVWebViewController needs to be contained in a UINavigationController. If you are presenting SVWebViewController modally, use SVModalWebViewController instead.");
	[super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden=YES;
    self.navigationController.toolbar.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 40, [UIScreen mainScreen].bounds.size.width, 40);
    [self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"foot_black"] forToolbarPosition:UIBarPositionBottom barMetrics:UIBarMetricsDefault];
	[self.navigationController.navigationBar addSubview:_progressView];
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        [self.navigationController setToolbarHidden:NO animated:animated];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_progressView removeFromSuperview];
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        [self.navigationController setToolbarHidden:YES animated:animated];
    }
}
#pragma mark - NJKWebViewProgressDelegate

-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
        [mainWebView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    }
    if (toInterfaceOrientation == UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
        [mainWebView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    }
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        [mainWebView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    }

}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        return YES;
    
    return toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}


#pragma mark - Toolbar

- (void)updateToolbarItems {
    self.backBarButtonItem.enabled = self.mainWebView.canGoBack;
    self.navigationItem.hidesBackButton = YES;
    self.forwardBarButtonItem.enabled = self.mainWebView.canGoForward;
    self.actionBarButtonItem.enabled = !self.mainWebView.isLoading;
    
    UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixedSpace.width = 5.0f;
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    NSArray *items;

    UIToolbar *toolbar = [[UIToolbar alloc] init];
    toolbar.items = items;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:toolbar];
            items = [NSArray arrayWithObjects:
                     fixedSpace,
                     self.backBarButtonItem, 
                     flexibleSpace,
                     self.forwardBarButtonItem,
                     flexibleSpace,
                     self.refreshBarButtonItem,
                     flexibleSpace,
                     self.homeBarButtonItem,
                     flexibleSpace,
                     flexibleSpace,
                     flexibleSpace,
                     flexibleSpace,
                     self.actionBarButtonItem,
                     fixedSpace,
                     nil];

        self.toolbarItems = items;
}

#pragma mark -
#pragma mark UIWebViewDelegate
- (BOOL)webView:(nonnull UIWebView *)webView shouldStartLoadWithRequest:(nonnull NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@",request);
    if ([request.URL isEqual:@"about:blank"]) {
        return NO;
    } else {
    return YES;
    }
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self updateToolbarItems];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    
    [self updateToolbarItems];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateToolbarItems];
}

#pragma mark - Target actions

- (void)goBackClicked:(UIButton *)sender {
    [mainWebView goBack];
}

- (void)goForwardClicked:(UIButton *)sender {
    [mainWebView goForward];
}

- (void)reloadClicked:(UIButton *)sender {
    [mainWebView reload];
}
- (void)homeClicked:(UIButton *)sender {
    [self loadWebView];
}
- (void)stopClicked:(UIBarButtonItem *)sender {
    [mainWebView stopLoading];
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	[self updateToolbarItems];
}

- (void)actionButtonClicked:(UIBarButtonItem *)sender {
    self.token = nil;
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    self.tabBarController.tabBar.hidden= NO;
    [self.navigationController popViewControllerAnimated:YES];

}


#pragma mark -
#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
    
	if([title isEqualToString:NSLocalizedString(@"Open in Safari", @"")])
        [[UIApplication sharedApplication] openURL:self.mainWebView.request.URL];
    
    if([title isEqualToString:NSLocalizedString(@"Copy Link", @"")]) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = self.mainWebView.request.URL.absoluteString;
    }
    
    else if([title isEqualToString:NSLocalizedString(@"Mail Link to this Page", @"")]) {
        
		MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
        
		mailViewController.mailComposeDelegate = self;
        [mailViewController setSubject:[self.mainWebView stringByEvaluatingJavaScriptFromString:@"document.title"]];
  		[mailViewController setMessageBody:self.mainWebView.request.URL.absoluteString isHTML:NO];
		mailViewController.modalPresentationStyle = UIModalPresentationFormSheet;
        
		[self presentModalViewController:mailViewController animated:YES];
	}
    
    pageActionSheet = nil;
}

#pragma mark -
#pragma mark MFMailComposeViewControllerDelegate

- (void)mailComposeController:(MFMailComposeViewController *)controller 
          didFinishWithResult:(MFMailComposeResult)result 
                        error:(NSError *)error 
{
	[self dismissModalViewControllerAnimated:YES];
}

@end
